import 'dart:ui';

import 'package:chewie/chewie.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/article_item.dart';
import 'package:flutter_syt/domain/news/video_controls.dart';
import 'package:flutter_syt/domain/widgets/flow_item.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/global_date_time_format.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:video_player/video_player.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "videoDetail")
class VideoDetailPage extends StatefulWidget {
  final String id;

  VideoDetailPage(this.id);

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailState();
  }
}

class _VideoDetailState extends State<VideoDetailPage> {
  var _isLoading = true;
  ArticleListItem? _item;
  List<ArticleListItem> _recommendList = [];

  VideoPlayerController? _playerController;
  ChewieController? _chewieController;

  @override
  void dispose() {
    _playerController?.pause();
    _playerController?.dispose();

    _chewieController?.pause();
    _chewieController?.dispose();
    // _playerController?.dispose()
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    setState(() {
      _isLoading = true;
    });
    try {
      print("the id is ${widget.id}");
      _recommendList = await API.shared.article.articleRecommend(widget.id);

      print('dalskjdlkasjdklasj   ${_recommendList.length}');

      _item = await API.shared.article.detail(widget.id);
      var source =
          VideoPlayerController.networkUrl(Uri.parse(_item?.video ?? ""));
      await source.initialize();
      _playerController = source;
      _chewieController = ChewieController(
        customControls: VideoCustomControls(() {
          Navigator.of(context).pop();
        }, false),
        autoPlay: true,
        deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
        videoPlayerController: source,
      );

      setState(() {
        _isLoading = false;
      });
    } catch (e, stack) {
      debugPrint("load error $e");
      debugPrint("load error $stack");
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget loading() {
    return Container(
      child: Center(
        child: Container(
          width: 100,
          height: 100,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.all(Radius.circular(8)),
          ),
          child: Theme(
            data: ThemeData(
                cupertinoOverrideTheme: CupertinoThemeData(
              brightness: Brightness.dark,
            )),
            child: CupertinoActivityIndicator(
              radius: 14,
            ),
          ),
        ),
      ),
    );
  }

  Widget body(ArticleListItem item) {
    Widget video = Container(
      color: Colors.black,
    );
    if (_playerController != null) {
      video = Chewie(
        controller: _chewieController!,
      );
    }
    List<SliverToBoxAdapter> recommendWidget = _recommendList.map((e) {
      var entity = FlowItemEntity();
      entity.createTime = e.publish_time;
      entity.text = e.title;
      entity.imageUrl = e.thumb;
      entity.linkUrl = e.linkUrl;
      entity.width = e.width;
      entity.height = e.height;

      return SliverToBoxAdapter(
        child: FlowItem(entity),
      );
    }).toList();
    var child = CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            child: Stack(
              clipBehavior: Clip.antiAlias,
              children: [
                Positioned.fill(
                  child: Image.network(
                    item.cover,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned.fill(
                  child: Container(
                    child: ClipRRect(
                      child: BackdropFilter(
                        filter: ImageFilter.blur(
                          sigmaY: 10,
                          sigmaX: 10,
                        ),
                        child: Container(
                          color: Colors.black54,
                        ),
                      ),
                    ),
                  ),
                ),
                SafeArea(
                  bottom: false,
                  child: Column(
                    children: [
                      AspectRatio(
                        aspectRatio: 16 / 9,
                        child: video,
                      ),
                      Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 15, vertical: 20),
                        child: Row(
                          children: [
                            Flexible(
                              child: Text(
                                item.title,
                                style: TextStyle(
                                  fontSize: 24,
                                  color: Colors.white,
                                  height: 1.5,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 20, horizontal: 15),
            child: Column(
              children: [
                Row(
                  children: [
                    Text(
                      item.author,
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.black.withOpacity(0.6),
                      ),
                    ),
                    Container(
                      width: 10,
                    ),
                    Text(
                      formatDate(item.publish_time),
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.black.withOpacity(0.6),
                      ),
                    ),
                  ],
                ),
                Container(
                  height: 15,
                ),
                Row(
                  children: [
                    Flexible(
                      child: Text(
                        item.description,
                        style: TextStyle(
                          fontSize: 16,
                          height: 1.375,
                          color: Colors.black.withOpacity(0.6),
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  height: 10,
                ),
              ],
            ),
          ),
        ),
        ...recommendWidget,
      ],
    );
    return child;
  }

  @override
  Widget build(BuildContext context) {
    Widget child;
    Widget header = SafeArea(
      bottom: false,
      child: Row(
        children: [
          Container(
            width: 20,
          ),
          GestureDetector(
            onTap: ClickUtils.debounce(() {
              Navigator.of(context).pop();
            }),
            child: Container(
              width: 36,
              height: 36,
              child: Image.asset("assets/icons/video_back.png"),
            ),
          ),
        ],
      ),
    );
    var item = _item;
    if (_isLoading) {
      child = Column(
        children: [
          header,
          Expanded(
            child: loading(),
          ),
          Container(
            height: 150,
          )
        ],
      );
    } else if (item != null) {
      child = body(item);
    } else {
      child = Container(
        child: Column(
          children: [
            header,
            Expanded(
              child: Container(
                padding: EdgeInsets.only(bottom: 200),
                child: ViewStateErrorWidget(
                  onPressed: () {
                    getData();
                  },
                ),
              ),
            ),
          ],
        ),
      );
    }
    return Scaffold(
      body: Container(
        child: child,
      ),
    );
  }
}
